package com.nhim.cms.dao;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.stereotype.Repository;

import com.nhim.cms.domain.Group;
import com.nhim.core.AppContext;
import com.nhim.core.dao.CoreDAO;

/**
 * A data access object (DAO) providing persistence and search support for Group
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 * @see .Group
 * @author Huy Lieu TA
 */
@Repository
public class GroupDAO extends CoreDAO<Integer, Group> implements IGroupDAO {
	// property constants
	public static final String NAME = "name";
	public static final String DESCRIPTION = "description";
	public static final String DOMAIN = "domain";
	public static final String PATH = "path";
	public static final String ERROR_URL = "errorUrl";

	@Autowired
	EntityManagerFactory entityManagerFactory;

	@PostConstruct
	public void init() {
		super.setEntityManagerFactory(entityManagerFactory);
	}

	
	public static IGroupDAO getFromApplicationContext(ApplicationContext ctx) {
		return (IGroupDAO) ctx.getBean(GroupDAO.class);
	}
	public static IGroupDAO getInstance()
	{
		return getFromApplicationContext(AppContext.getApplicationContext());
	}


	@SuppressWarnings("unchecked")
	public List<Group> findByProperty(String propertyName, final Object value) {
					
			try {
				final String queryString = "select model from Group model where model."
						+ propertyName + "= :propertyValue";
				return getJpaTemplate().executeFind(new JpaCallback<Object>() {
					public Object doInJpa(EntityManager em)
							throws PersistenceException {
						Query query = em.createQuery(queryString);
						query.setParameter("propertyValue", value);
						return query.getResultList();
					}
				});
			} catch (RuntimeException re) {
				throw re;
			}

	}

}